﻿using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;
namespace BTVPodcatcherNamespace
{
    public partial class FeedSetup : Form
    {


	
        RSSLibrary3.RSSFeed editingFeed = null;
        public FeedSetup()
        {
            InitializeComponent();
            BTVIntergrationDD.SelectedIndex = 0;
            RemoveItemsDD.SelectedIndex = 0;
            DownloadBassedOn.SelectedIndex = 0;
            MaximinNumberDD.SelectedIndex = 0;
            ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors ) {
			return true;
	        };
        }

        private void button2_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = SaveToTXTBX.Text;
            if (folderBrowserDialog1.ShowDialog().Equals(DialogResult.OK))
            {
                SaveToTXTBX.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveToTXTBX.Text = comboBox1.SelectedItem.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (validateForm())
            {
                errorProvider1.Clear();
                RSSLibrary3.DownloadNewOn dno = RSSLibrary3.DownloadNewOn.NewGUID;
                switch (DownloadBassedOn.SelectedIndex)
                {
                    case 0: dno = RSSLibrary3.DownloadNewOn.NewGUID;
                        break;
                    case 1: dno = RSSLibrary3.DownloadNewOn.NewFileName;
                        break;
                    case 2: dno = RSSLibrary3.DownloadNewOn.Date;
                        break;
                    case 3: dno = RSSLibrary3.DownloadNewOn.DoNotDowload;
                        break;
                    default: dno = RSSLibrary3.DownloadNewOn.DoNotDowload;
                        break;
                }
                bool btvIntergration = false;
                if (BTVIntergrationDD.SelectedIndex == 0)
                {
                    btvIntergration = true;
                }
                bool removeItems = true;
                if (RemoveItemsDD.SelectedIndex == 1)
                {
                    removeItems = false;
                }
                if (editingFeed == null)
                {
                    RSSLibrary3.RSSFeed rsf = new RSSLibrary3.RSSFeed(feedURLTXTBX.Text, btvIntergration, removeItems, dno, MaximinNumberDD.SelectedIndex - 1, SaveToTXTBX.Text);
                    ((MainForm)this.MdiParent).rssFeeds.Add(rsf);
                    if (rsf.exception != null)
                    {
                        ConsoleForm.addMessage("Feed Update Exception " + rsf.exception);
                    }
                    ConsoleForm.addMessage("New Feed Added");
                }
                else
                {
                    editingFeed.saveSetupChange(feedURLTXTBX.Text, btvIntergration, removeItems, dno, MaximinNumberDD.SelectedIndex - 1, SaveToTXTBX.Text);
                    if (editingFeed.exception != null)
                    {
                        ConsoleForm.addMessage("Feed Update Exception " + editingFeed.exception);
                    }
                    editingFeed = null;
                    ConsoleForm.addMessage("Feed updated");
                }
                resetForm();
                rSSFeedBindingSource.ResetBindings(false);
                ((MainForm)this.MdiParent).writeBTVFeedFile();
            }
        }
        public void loadBTVFolders()
        {
            rSSFeedBindingSource.DataSource = ((MainForm)this.MdiParent).rssFeeds;
            try
            {
                
                
                
                string _serverName = "http://" + ((MainForm)this.MdiParent).BTVServer.Trim() + ":" + ((MainForm)this.MdiParent).BTVPort;
                if (((MainForm)this.MdiParent).useSSL)
                {
                    _serverName = "https://" + ((MainForm)this.MdiParent).BTVServer.Trim() + ":" + ((MainForm)this.MdiParent).BTVPort;
                }
                string _password = ((MainForm)this.MdiParent).BTVPassword;
                string _username = ((MainForm)this.MdiParent).BTVUsername;
                BTVLicenseManager.BTVLicenseManager lm = new BTVLicenseManager.BTVLicenseManager();
                lm.Url = _serverName + "/wsdl/BTVLicenseManager.asmx";
                //  if (((MainForm)this.MdiParent).BTVServer.Trim().Equals("127.0.0.1") || ((MainForm)this.MdiParent).BTVServer.Trim().ToLower().Equals("localhost"))
                //   lm.Logon("", _password);
                BTVLicenseManager.PVSPropertyBag pvspb = lm.Logon("", _username, _password);
                string autTicket = "";
                foreach (BTVLicenseManager.PVSProperty pvp in pvspb.Properties)
                {
                    if (pvp.Name.Equals("AuthTicket"))
                    {
                        autTicket = pvp.Value;
                    }
                }
                //  lm.LogonRemote("", _password);
                BTVLibrary.BTVLibrary lib = new BTVLibrary.BTVLibrary();
                lib.Url = _serverName + "/wsdl/BTVLibrary.asmx";

                BTVLibrary.PVSPropertyBag[] topfolders = lib.GetFolders(autTicket, "");
                foreach (BTVLibrary.PVSPropertyBag folder in topfolders)
                {

                    foreach (BTVLibrary.PVSProperty prop in folder.Properties)
                    {
                        Console.WriteLine("Prop Name " + prop.Name + " value " + prop.Value);
                        if (prop.Name.Equals("FullName"))
                        {
                            comboBox1.Items.Add(prop.Value);
                        }

                    }
                }
                lm.Logoff(autTicket);
                if(comboBox1.Items.Count>0)
                    comboBox1.SelectedIndex = 0;
                SaveToTXTBX.Text = comboBox1.SelectedItem.ToString();

            }
            catch (Exception e3)
            {
                
                BTVIntergrationDD.SelectedItem = "No";
                BTVIntergrationDD.Enabled = false;
                ConsoleForm.addMessage("Error Loading BTV Folders \r\n"+e3.ToString());
            }
        }

        private void BTVIntergrationDD_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (BTVIntergrationDD.SelectedIndex == 0)
            {
                comboBox1.Visible = true;
                SaveToTXTBX.Visible = false;
                button2.Visible = false;
            }
            else
            {
                comboBox1.Visible = false;
                SaveToTXTBX.Visible = true;
                button2.Visible = true;
            }
        }

        private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            System.Console.WriteLine("");
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            System.Console.WriteLine("");
           // dataGridView1.DataMember[0];
            if(e.RowIndex>=0)
            {
                editingFeed = (RSSLibrary3.RSSFeed)rSSFeedBindingSource.Current;
                feedURLTXTBX.Text = editingFeed.feedURL;
                switch (editingFeed.downlaodOn)
                {
                    case  RSSLibrary3.DownloadNewOn.NewGUID:
                        DownloadBassedOn.SelectedIndex = 0;
                        break;
                    case  RSSLibrary3.DownloadNewOn.NewFileName:
                        DownloadBassedOn.SelectedIndex = 1;
                        break;
                    case   RSSLibrary3.DownloadNewOn.Date:
                        DownloadBassedOn.SelectedIndex = 2;
                        break;
                    case RSSLibrary3.DownloadNewOn.DoNotDowload:
                        DownloadBassedOn.SelectedIndex = 3;
                        break;
                    default :
                        DownloadBassedOn.SelectedIndex = 4;
                        break;
                }
                if (editingFeed.btvIntergration && BTVIntergrationDD.Enabled)
                {
                    BTVIntergrationDD.SelectedIndex = 0;
                }
                else
                {
                    BTVIntergrationDD.SelectedIndex = 1;
                }
                
                if(editingFeed.removeItems)
                {
                    RemoveItemsDD.SelectedIndex = 0;
                }else
                {
                    RemoveItemsDD.SelectedIndex = 1;
                }
                MaximinNumberDD.SelectedIndex = editingFeed.maxToDownload+1;
                if (comboBox1.Items.Contains(editingFeed.saveLocation))
                {
                    comboBox1.SelectedItem = editingFeed.saveLocation;
                }
                SaveToTXTBX.Text = editingFeed.saveLocation;
                CancelB.Visible = true;
                DeleteB.Visible = true;

            }

        }

        private void CancelB_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            resetForm();
        }

        private void resetForm()
        {

            editingFeed = null;
            SaveToTXTBX.Text = "";
            if (BTVIntergrationDD.Enabled)
            {
                BTVIntergrationDD.SelectedIndex = 0;
                if (comboBox1.Items.Count > 0)
                    comboBox1.SelectedIndex = 0;
            }
            else
            {
                BTVIntergrationDD.SelectedIndex = 1;
            }
            RemoveItemsDD.SelectedIndex = 0;
            DownloadBassedOn.SelectedIndex = 0;
            MaximinNumberDD.SelectedIndex = 0;
            feedURLTXTBX.Text = "";
            if(comboBox1.SelectedItem!=null)
                SaveToTXTBX.Text = comboBox1.SelectedItem.ToString();
            CancelB.Visible = false;
            DeleteB.Visible = false;
        }

        private void DeleteB_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (MessageBox.Show("Are You Sure You Want to Delete the Feed Setup", "Are You Sure", MessageBoxButtons.YesNo).Equals(DialogResult.Yes))
            {
                ((MainForm)this.MdiParent).rssFeeds.Remove(editingFeed);
                resetForm();
                rSSFeedBindingSource.ResetBindings(false);
            }
        }
        private bool validateForm()
        {
            bool value = true;
            if (feedURLTXTBX.Text.Trim().Equals(""))
            {
                errorProvider1.SetError(feedURLTXTBX, "Please Enter a Feed URL");
                value = false;
            }
            try
            {
                if (SaveToTXTBX.Text.Trim().Equals(""))
                {
                    value = false;
                    if (SaveToTXTBX.Visible)
                    {
                        errorProvider1.SetError(SaveToTXTBX, "Please Enter a Vaild Save To Location");
                    }
                    else
                    {
                        errorProvider1.SetError(comboBox1, "Please Enter a Vaild Save To Location");
                    }
                }
                else if (!System.IO.Directory.Exists(SaveToTXTBX.Text))
                {
                    value = false;
                    if (SaveToTXTBX.Visible)
                    {
                        errorProvider1.SetError(SaveToTXTBX, "Please Enter a Vaild Save To Location");
                    }
                    else
                    {
                        errorProvider1.SetError(comboBox1, "Please Enter a Vaild Save To Location");
                    }
                }
            }
            catch (Exception)
            {
                value = false;
                if (SaveToTXTBX.Visible)
                {
                    errorProvider1.SetError(SaveToTXTBX, "Please Enter a Vaild Save To Location");
                }
                else
                {
                    errorProvider1.SetError(comboBox1, "Please Enter a Vaild Save To Location");
                }
            }
            return value;
        }
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value.Equals(RSSLibrary3.DownloadNewOn.NewGUID))
            {
                e.Value = "GUID";
                e.FormattingApplied = true;
            }
            else if (e.Value.Equals(RSSLibrary3.DownloadNewOn.NewFileName))
            {
                e.Value = "Filename";
                e.FormattingApplied = true;
            }
            else if (e.Value.Equals(RSSLibrary3.DownloadNewOn.DoNotDowload))
            {
                e.Value = "Do Not Download";
                e.FormattingApplied = true;
            }

        }

        
    }
}
